﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sprint1.Models;
using System.Web.Security;
using PagedList;
using PagedList.Mvc;
using System.Text;

namespace Sprint1.Controllers
{
    public class InstructorController : Controller
    {
        #region Hamed
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Register()
        {
            //Log out the user if he was logged in 
            bool user = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
            if (user)
            {
                FormsAuthentication.SignOut();
            }
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(Instructor instructor)
        {

            if (ModelState.IsValid)
            {
                try
                {
                    #region new user
                    using (StudyDatabaseEntities dc = new StudyDatabaseEntities())
                    {
                        var query = from st in dc.Instructors
                                    where st.Email == instructor.Email
                                    select st;
                        var exists = query.SingleOrDefault();
                        if (exists == null)
                        {
                            dc.Instructors.Add(instructor);
                            dc.SaveChanges();
                            ModelState.Clear();
                            ViewBag.messege = "Created Successfully";
                        }
                        else
                        {
                            ViewBag.messege = string.Format("{0} Already Exists ", instructor.Email);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {///////////////////Developer Comment //////////////////////
                    ViewBag.messege = ex.InnerException.Message;
                }
            }
            return View();

        }
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(InstructorLoginModel instructor)
        {
            if (ModelState.IsValid)
            {
                using (StudyDatabaseEntities db = new StudyDatabaseEntities())
                {
                    var exists = db.Instructors.Where(st => st.Email.Equals(instructor.Email) && st.Password.Equals(instructor.Password)).FirstOrDefault();
                    if (exists != null)
                    {
                        //will always redirect to default if i didn't pass new { ReturnUrl = Request.QueryString["ReturnUrl"] }
                        //with the HTML  form 
                        //http://stackoverflow.com/questions/4246606/formsauthentication-getredirecturl-always-returns-the-default
                        FormsAuthentication.SetAuthCookie(exists.Email, true);
                        return Redirect("CreateCourse");
                    }
                    else
                    {
                        ViewBag.message = "Invalid Email or Password ";
                    }
                }
            }
            else//modelstate is not valid 
            {
                var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            }
            return View(instructor);
        }
        #endregion

        #region Hagar
        /////////////////////////////////INSTRUCTOR ID WHEN LOGIN AND REGISTER with SESSION ////////////////////////////////////////////////////
        //Session.Contents.RemoveAll()
        StudyDatabaseEntities db = new StudyDatabaseEntities();
       [Authorize]
        public ActionResult MyCourses()
        {
            string email = HttpContext.User.Identity.Name.ToString();
            int instructorid = db.Instructors.SingleOrDefault(s => s.Email == email).Id;
            return View(db.Instructors.Single(i => i.Id == instructorid).Courses.ToList());
        }
        [Authorize]
        public ActionResult CourseDetails(int? CourseId)
        {
            if (CourseId==null)
            {
                return RedirectToAction("MyCourses");   
            }
            return View(db.Courses.Single(C => C.Id == CourseId));
        }
        [Authorize]
        public ActionResult CreateCourse()
        {
            return View();
        }
        [HttpPost]
        [Authorize]
        public ActionResult CreateCourse(Course course)
        {
            string email = HttpContext.User.Identity.Name.ToString();
            int instructorid = db.Instructors.SingleOrDefault(s => s.Email == email).Id;
            if (ModelState.IsValid)
            {
                try
                {
                    course.Instructors.Add(db.Instructors.Single(i => i.Id == instructorid));
                    db.Courses.Add(course);
                    db.Instructors.Single(i => i.Id == instructorid).Courses.Add(course);
                    db.SaveChanges();

                }
                catch (Exception e)
                {
                    ViewBag.message = e.Message;
                }
                return RedirectToAction("MyCourses");
            }

            return View();
        }
        #endregion
        #region Hamed2
        [HttpGet]
        public ActionResult Announce()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Announce(int? CourseId, Anouncement anouncement)
        {
            if (CourseId < 0 || CourseId == null)
            {
                ViewBag.message = "invalid url ! ! ";
                return View();
            }
            else
            {
                if (ModelState.IsValid)
                {
                    string email = HttpContext.User.Identity.Name.ToString();
                    try
                    {
                        anouncement.Announcer = db.Instructors.SingleOrDefault(s => s.Email == email).Name;
                        Course current = db.Courses.SingleOrDefault(s => s.Id == CourseId);
                        anouncement.Courses.Add(current);//add course to announcements
                        db.Anouncements.Add(anouncement);
                        current.Anouncements.Add(anouncement);//add announcement to course 
                        db.SaveChanges();
                        ViewBag.message = "Posted";
                        foreach (Student student in current.Students)
                        {
                            StringBuilder emailBody = new StringBuilder();
                            emailBody.Append(string.Format("Dear <b> {0} </b><br/> ", student.Name));
                            emailBody.Append(string.Format("Instructor<b> {0} </b> has posted an announcement on Course<b> {1}</b> <br/>", anouncement.Announcer, current.Name));
                            emailBody.Append(string.Format(" {0} <br/>", anouncement.Title));
                            emailBody.Append(anouncement.Description);
                            EmailSystem.SendEmail(student.Email, emailBody.ToString(), current.Name);
                        }
                        return View();
                    }
                    catch (Exception ex)
                    {
                        ViewBag.message = ex.Message;
                        return View();
                    }
                }
                else
                {
                    ViewBag.message = "modelstate not valid ";
                    return View();
                }
            }
        }
        [HttpGet]
        public ActionResult Announcements(int? CourseId, int? page)
        {
            if (CourseId < 0 || CourseId == null)
            {
                ViewBag.message = "invalid url ! ! ";
                return View();
            }
            else
            {
                using (StudyDatabaseEntities dc = new StudyDatabaseEntities())
                {
                    Course current = dc.Courses.SingleOrDefault(s => s.Id == CourseId);
                    return View(current.Anouncements.ToPagedList(page ?? 1, 3));
                }
            }
        }
        #endregion
    }
}